import useMessage from "@/utils/useMessage.ts";
import routes from '@/router/modules/dashboard.ts'
import adminRoutes from '@/router/modules/admin.ts'
import {useOrgStore} from "@/store/modules/organization";

interface PermissionItem{
    title:string |undefined,
    icon:any,
    key:string|undefined,
    actions:string[] | undefined
}
interface PermissionsType {
    workbench:PermissionItem[],
    admin:PermissionItem[]
}
export const getPermissions = ()=>{
    const workbench = routes.filter(item=>item.name !== 'Admin')
    const admin = adminRoutes.filter(item=>item.name !== 'adminConfig' && item.name !== 'adminOther') ?? []
    const appsRouter = adminRoutes.filter(item=>item.name === 'adminConfig' || item.name === 'adminOther')
    const apps = appsRouter[0]?.children || []
    const other = appsRouter.length > 1 ? appsRouter[1]?.children || [] : []
    //将apps和other合并到admin中
    const mergedAdmin = [...admin, ...apps, ...other];
    
    const permissions:PermissionsType = {
        workbench: workbench.map(item => ({
            title: item.meta?.title || '',
            icon: item.meta?.icon,
            key: item.meta?.permission,
            actions: item.meta?.actions
        })),
        admin: mergedAdmin.map(child => ({
            title: child.meta?.title,
            icon: child.meta?.icon,
            key: child.meta?.permission,
            actions: child.meta?.actions
        }))
    }
    
    return permissions
}
/**
 * 按钮级权限控制
 * @param key 权限标识 ['model:key']||['model:key:action']
 */
export const hasPermission = (key:string)=>{
    const orgStore = useOrgStore()
    const permissions = orgStore.data?.permissions
    
    // 如果没有权限数据，默认允许访问
    if (!permissions) return true;
    
    // 检查是否为超级管理员(拥有所有权限)
    if (permissions.includes("*:*:*") && orgStore.data?.role_slug === 'owner') return true;
    
    // 检查是否拥有特定权限
    if (permissions.includes(key)) return true;

    // 没有权限，提示并返回false
    useMessage(403, '您没有权限执行此操作!');
    return false;
}

export const getPermActionText = (permission: string) => {
    const textArr: Record<string, string> = {
        'create': '添加',
        'update': '编辑',
        'delete': '删除',
        'export': '导出',
        'import': '导入',
        'download': '下载',
        'upload': '上传',
        'print': '打印',
        'query': '搜索'
    };

    const parts = permission.split(':');
    const action = parts[parts.length - 1];
    return textArr[action as keyof typeof textArr] || action;
};